package com.springbootblog.service.serviceImpl.fontend;

import com.springbootblog.controller.fontend.IndexController;
import com.springbootblog.dao.ArticleDao;
import com.springbootblog.dao.MessageDao;
import com.springbootblog.dao.UserDao;
import com.springbootblog.dao.WebsetDao;
import com.springbootblog.pojo.*;
import com.springbootblog.service.fontend.ArticleService;
import com.springbootblog.utils.AES;
import com.springbootblog.utils.Email;
import com.springbootblog.utils.Function;
import com.springbootblog.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService
{
    /**
     * 定义一个静态常量日志对象
     */
    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    /**
     * 自动装载（dao接口注入）
     */
    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private WebsetDao websetDao;

    @Value("${spring.AES.key}")
    public String key;
    @Value("${spring.AES.iv}")
    public String iv;

    /**
     * 获取文章详情
     * @param article_id
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> getArticleDetail(String article_id, HttpServletRequest request) throws Exception
    {
        // 参数判断
        if(article_id == "" || article_id == null)
        {
            Map<String, Object> result = new HashMap<>(2);
            result.put("code",-1);
            result.put("msg","参数错误！");
            return result;
        }

        // 获取session
        // HttpSession session = request.getSession();
        // 获取token
        String token = request.getHeader(JwtUtils.token_name);
        // 解析token
        Claims paramList = JwtUtils.parseJWT(token);
        Object usernames;
        Object username;
        if(paramList == null || paramList.equals(null))
        {
            usernames = null;
            username = null;
        }
        else
        {
            usernames = paramList.get("nickname");
            username = paramList.get("nickname");
        }
        // 查网站设置信息
        Webset webset = websetDao.getWebsetInfo();
        // System.out.println(webset.toString());
        String isLoginLook = webset.getIs_login_look();
        if(isLoginLook.equals("1"))
        {
            // Object usernames = session.getAttribute("nickname");
            //Object usernames = paramList.get("nickname");
            if(usernames == null || usernames.equals("") || !usernames.equals("camellia"))
            {
                Map<String, Object> result = new HashMap<>();
                result.put("code",50);
                result.put("msg","您没有权限访问，请登录！");
                result.put("username",usernames);
                return result;
            }
        }
        // 前端AES加密，后端AES解密
        String str = AES.decryptAES(article_id,this.key,this.iv);
        // 获取key对应的值
        article_id = Function.stringToJson(str,"article_id");

        // System.out.println(article_id);
        Article detail = articleDao.getArticleDetailById(article_id);
        String html = detail.getContent();
        // 将字符串转换成文档对象
        Document doc = Jsoup.parse(html);
        // 选择所有tag为"img"的元素并遍历输出其文本内容
        Elements elementsByTag = doc.getElementsByTag("img");
        // 循环所有的img标签对象~
        for (Integer i= 0; i < elementsByTag.size(); i++)
        {
            doc.getElementsByTag("img").get(i).attr("class","cursor");
            doc.getElementsByTag("img").get(i).attr("onclick","imageBoost('"+doc.getElementsByTag("img").get(i).attr("src")+"')");
            doc.getElementsByTag("img").get(i).attr("style","width:100%");
        }
        String outHtml = doc.outerHtml();
        detail.setContent(outHtml);
        // 所属标签
        String labelstr = Function.removeStrChars(detail.getLabelstr(),',');
        System.out.println(labelstr);
        Object labelList = "";
        if(labelstr.equals(null) == false && labelstr.isEmpty() == false)
        {
            labelList = articleDao.getLabelByIdStr(labelstr);
        }
        // 上一篇文章
        Article front = articleDao.getFrontArticle(article_id);
        // 下一篇文章
        Article after = articleDao.getAfterArticle(article_id);
        // 查询文章评论
        Map<String, Object> data = this.getCommentList(article_id);
        Object commentList = data.get("commentList");
        Object commentCount = data.get("commentCount");

        // 资源列表
        Object resource = "";
        if(detail.getResourse_id() != 0)
        {
            resource = articleDao.getResourceById(detail.getResourse_id());
        }
        // 写浏览记录
        //Object username = session.getAttribute("nickname");
        //Object username = paramList.get("nickname");
        if(username == null || username.equals(""))
        {
            username = "游客";
        }
        // 获取当前访问ip
        String ip = Function.getIpAddress(request);
        Browse browse = new Browse();
        browse.setUsername(username.toString());
        browse.setArticleTitle(detail.getArttitle());
        browse.setIp(ip);
        browse.setIsWeixin((byte) '0');
        Integer res = articleDao.addBrowse(browse);
        // 获取自增主键
        Integer id = browse.getId();

        // 访问量 + 1
        Integer r = articleDao.addClickNum(detail.getId().toString());

        Map<String, Object> result = new HashMap<>(9);
        result.put("code",1);
        result.put("msg","获取成功");
        result.put("detail",detail);
        result.put("front",front);
        result.put("after",after);
        result.put("labelList",labelList);
        result.put("commonList",commentList);
        result.put("commentCount",commentCount);
        result.put("resource",resource);
        return result;

    }

    @Resource
    private Email emailObj;

    /**
     * 提交评论
     * @param article_id
     * @param email
     * @param content
     * @param content_reply
     * @param replyid
     * @param request
     * @return
     */
    @Override
    public Map<String, Object> putComment(String article_id, String email, String content, String content_reply, String replyid, HttpServletRequest request) throws Exception {
        //获取session对象
        // HttpSession session = request.getSession();
        // 获取token
        String token = request.getHeader(JwtUtils.token_name);
        // 解析token
        Claims paramList = JwtUtils.parseJWT(token);
        // 用户id
        Integer id;
        if(paramList == null || paramList.equals(null))
        {
            id = 0;
        }
        else
        {
            id = (Integer) paramList.get("id");
        }
        if(id == 0 || id == null)
        {
            Map<String, Object> result = new HashMap<>(2);
            result.put("code", -1);
            result.put("msg", "您未登录！");
            return result;
        }
        // 用户id
        // String email_session = (String) session.getAttribute("email");
        String email_session = (String) paramList.get("email");
        // 如果邮箱字段有值，说明当前用户没有绑定邮箱，将邮箱写入数据库
        if(email != null && !email.isEmpty())
        {
            messageDao.updateUserInfo(id.toString(), email);
        }
        else if(email_session != null && !email_session.isEmpty())
        {
            email = email_session;
        }
        else
        {
            Map<String, Object> result = new HashMap<>(2);
            result.put("code", -2);
            result.put("msg", "请填写您的邮箱！");
            return result;
        }
        // 前端AES加密，后端AES解密
        String str = AES.decryptAES(article_id,this.key,this.iv);
        // 获取key对应的值
        article_id = Function.stringToJson(str,"article_id");
        if((content_reply == null || content_reply.isEmpty()) && (content == null || content.isEmpty()))
        {
            Map<String, Object> result = new HashMap<>(2);
            result.put("code", -3);
            result.put("msg", "请填写您的评论内容！");
            return result;
        }
        // 评论内容
        if(content == null || content.isEmpty())
        {
            content = content_reply;
        }
        // 回复评论id
        if(replyid == null || replyid.isEmpty())
        {
            replyid = "0";
        }
        String returnid = "0";
        String reply_user_id = "0";
        // 判断回复那条朱评论的id
        if(!replyid.equals("0"))
        {
            Comment returnInfo = articleDao.getCommentInfo(replyid);
            if(returnInfo.getReturnid() == 0)
            {
                returnid = replyid;
            }
            else
            {
                returnid = returnInfo.getReturnid().toString();
            }
            reply_user_id = returnInfo.getUid().toString();
        }
        // 回复 -> 自己不给自己发邮件
        if(!id.toString().equals(reply_user_id))
        {
            Article articleInfo = articleDao.getArticleDetailById(article_id);
            String mailto = "";
            String subject = "";
            String body = "";
            // reply_user_id 为 0 时是评论，否则为回复
            if(reply_user_id.equals("0"))
            {
                if (id != 1) {
                    mailto = "805795955@qq.com"; //收件人
                    subject = "时间里的博客评论"; //邮件主题
                    body = "您在时间里的博客《" + articleInfo.getArttitle() + "》文章收到评论，内容为“" +content+ "”"; //邮件内容
                }
            }
            else
            {
                User userInfo = userDao.getUserInfoById(reply_user_id);
                if(userInfo != null)
                {
                    mailto = userInfo.getEmail();
                    subject = "时间里的博客评论"; //邮件主题
                    body = "您在时间里的博客《" + articleInfo.getArttitle() + "》文章收到评论，内容为“" +content+ "”"; //邮件内容
                }
            }
            emailObj.sendSimpleMail(mailto,subject,body);
        }
        Comment comment = new Comment();
        comment.setUid(id);
        comment.setReplyid(Integer.parseInt(replyid));
        comment.setContent(content);
        comment.setReturnid(Integer.parseInt(returnid));
        comment.setArticle_id(Integer.parseInt(article_id));
        Integer res = articleDao.addComment(comment);
        Map<String, Object> result = new HashMap<>(2);
        result.put("code", 1);
        result.put("msg", "操作成功!");
        return result;
    }

    /**
     * 获取评论列表
     * @param article_id
     * @return
     * @throws Exception
     */
    public Map<String, Object> getCommentList(@RequestParam(defaultValue = "") String article_id) throws Exception
    {
        Integer commentCount = 0;
        List<Comment> commentList = articleDao.getCommontListByArticleId(article_id);
        if(commentList.size() == 0)
        {
            Map<String, Object> result = new HashMap<>(2);
            result.put("commentList",commentList);
            result.put("commentCount",commentCount);
            return result;
        }
        for (int i = 0; i < commentList.size(); i++)
        {
            String figureurl_qq = commentList.get(i).getFigureurl_qq();
            String figureurl_wx = commentList.get(i).getFigureurl_wx();

            if(figureurl_qq !=  null && figureurl_qq != "")
            {
                commentList.get(i).setFigureurl_qq(figureurl_qq);
            }
            else if(figureurl_wx !=  null && figureurl_wx != "")
            {
                commentList.get(i).setFigureurl_qq(figureurl_wx);
            }
            commentCount++;
            String comment_id = commentList.get(i).getId().toString();
            List<Comment> com_two = articleDao.getCommontTwoListByArticleId(article_id,comment_id);
            if(com_two.size() > 0)
            {
                for (int j = 0; j < com_two.size(); j++)
                {
                    String figureurl_qq_two = com_two.get(j).getFigureurl_qq();
                    String figureurl_wx_two = com_two.get(j).getFigureurl_wx();

                    if(figureurl_qq_two !=  null && figureurl_qq_two != "")
                    {
                        com_two.get(j).setFigureurl_qq(figureurl_qq_two);
                    }
                    else if(figureurl_wx_two !=  null && figureurl_wx_two != "")
                    {
                        com_two.get(j).setFigureurl_qq(figureurl_wx_two);
                    }
                    commentCount++;
                    String replyid =  com_two.get(j).getReplyid().toString();
                    Comment userinfo = articleDao.getCommontByReplyId(replyid);
                    if(userinfo != null)
                    {
                        Object nickname = userinfo.getNickname();

                        if(nickname != null && nickname != "")
                        {
                            com_two.get(j).setReply_nickname(nickname.toString());
                        }
                        if(userinfo.getFigureurl_qq() != "" && userinfo.getFigureurl_qq() != null)
                        {
                            com_two.get(j).setReply_figureurl_qq(userinfo.getFigureurl_qq());
                        }
                        else if(userinfo.getFigureurl_wx() != "" && userinfo.getFigureurl_wx() != null)
                        {
                            com_two.get(j).setReply_figureurl_qq(userinfo.getFigureurl_wx());
                        }
                        commentList.get(i).setCom_two(com_two);
                    }
                }
            }
        }
        Map<String, Object> result = new HashMap<>(2);
        result.put("commentList",commentList);
        result.put("commentCount",commentCount);
        return result;
    }
}

